package com.zrrd.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.zrrd.reggie.util.BaseContext;
import com.zrrd.reggie.util.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    //路径匹配器
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;
        String requestURI = req.getRequestURI();
        System.out.println("拦截到了请求====>"+requestURI);
        String[] urls={
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        boolean check=this.check(urls,requestURI);
        if(check){
            filterChain.doFilter(req,resp);
            return;
        }
        Long empId=(Long) req.getSession().getAttribute("empId");
        if(empId!=null){
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(req,resp);
            return;
        }

        Long userId = (Long) req.getSession().getAttribute("userId");
        if(userId!=null){
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(req,resp);
            return;
        }

        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    public boolean check(String[] urls,String requestUrl){
        for (String url : urls) {
            boolean match=PATH_MATCHER.match(url,requestUrl);
            if(match){
                return match;
            }
        }
        return false;
    }
}
